import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'motility.dart';
import 'configuration.dart';
import 'motility_analysis_result.dart';

/// 使用示例：如何使用Flutter版本的Motility类
class MotilityExample {
  
  /// 示例：基本使用
  static Future<void> basicUsage() async {
    print('=== 基本使用示例 ===');
    
    // 1. 创建配置
    final config = Configuration(
      regGrayThreshold: 255.0,
      regMaxSize: 200,
      regMinSize: 30,
      grayKernalSize: 7.0,
      grayAlpha: 1.0,
      grayBeta: 5.0,
      grayBlurredSize: 5,
      grayMaxValue: 255,
      grayBlockSize: 37,
      grayCThreshold: 2.0,
      showAreaSize: false,
      showSpermBox: false,
      cropFrame: true,
      trackSpermOnly: false,
      markRegBorder: false,
      saveCapturedVideoToPhotos: true,
      saveProceedImgsToPhotos: false,
      debugMode: false,
      totalTiming: 300,
      totalLiquifyingTiming: 600,
      deviceIP: "192.168.3.1",
      tempCheckInterval: 1200,
      matchDistance: 28,
      segmentCount: 3,
      segmentDuration: 1.0,
    );
    
    // 2. 创建Motility实例
    final motility = Motility(config: config);
    
    // 3. 分析视频
    final videoPath = await _getSampleVideoPath();
    if (videoPath != null) {
      print('开始分析视频: $videoPath');
      
      final result = await motility.analyze(videoPath);
      
      if (result != null) {
        print('分析完成！');
        print('检测到的精子数量: ${result.numOfDetectedSperms}');
        print('A级精子数量: ${result.numOfALevelSperms}');
        print('B级精子数量: ${result.numOfBLevelSperms}');
        print('C级精子数量: ${result.numOfCLevelSperms}');
        print('活动轨迹数量: ${result.numOfMotileTrajectories}');
        print('平均总位移: ${result.avgTotalDisplacement.toStringAsFixed(2)}');
        print('平均VSL: ${result.avgVsl.toStringAsFixed(2)}');
        print('平均VCL: ${result.avgVcl.toStringAsFixed(2)}');
        print('平均VAP: ${result.avgVap.toStringAsFixed(2)}');
        print('平均ALH: ${result.avgAlh.toStringAsFixed(2)}');
      } else {
        print('分析失败或没有检测到精子');
      }
    } else {
      print('未找到示例视频文件');
    }
  }
  
  /// 示例：自定义配置
  static Future<void> customConfiguration() async {
    print('=== 自定义配置示例 ===');
    
    // 创建自定义配置
    final customConfig = Configuration(
      regGrayThreshold: 200.0,  // 降低灰度阈值
      regMaxSize: 150,          // 减小最大尺寸
      regMinSize: 20,           // 减小最小尺寸
      grayKernalSize: 5.0,      // 减小核大小
      grayBlurredSize: 3,       // 减小模糊大小
      grayBlockSize: 25,        // 减小块大小
      showSpermBox: true,       // 显示精子框
      cropFrame: false,         // 不裁剪帧
      trackSpermOnly: true,     // 只跟踪精子
      saveCapturedVideoToPhotos: false,  // 不保存视频
      saveProceedImgsToPhotos: true,     // 保存处理后的图片
      debugMode: true,          // 启用调试模式
      segmentCount: 5,          // 增加片段数量
      segmentDuration: 0.5,     // 减少片段时长
    );
    
    final motility = Motility(config: customConfig);
    
    final videoPath = await _getSampleVideoPath();
    if (videoPath != null) {
      print('使用自定义配置分析视频...');
      final result = await motility.analyze(videoPath);
      
      if (result != null) {
        print('自定义配置分析完成！');
        print('结果: $result');
      }
    }
  }
  
  /// 示例：批量处理
  static Future<void> batchProcessing() async {
    print('=== 批量处理示例 ===');
    
    final config = Configuration();
    final motility = Motility(config: config);
    
    // 获取多个视频文件
    final videoPaths = await _getMultipleVideoPaths();
    
    if (videoPaths.isNotEmpty) {
      final results = <MotilityAnalysisResult>[];
      
      for (int i = 0; i < videoPaths.length; i++) {
        print('处理视频 ${i + 1}/${videoPaths.length}: ${videoPaths[i]}');
        
        final result = await motility.analyze(videoPaths[i]);
        if (result != null) {
          results.add(result);
          print('视频 ${i + 1} 处理完成');
        } else {
          print('视频 ${i + 1} 处理失败');
        }
      }
      
      // 汇总结果
      if (results.isNotEmpty) {
        print('\n=== 批量处理汇总 ===');
        print('总处理视频数: ${videoPaths.length}');
        print('成功处理数: ${results.length}');
        print('失败处理数: ${videoPaths.length - results.length}');
        
        // 计算平均值
        final avgDetectedSperms = results.fold<int>(0, (sum, r) => sum + r.numOfDetectedSperms) ~/ results.length;
        final avgALevelSperms = results.fold<int>(0, (sum, r) => sum + r.numOfALevelSperms) ~/ results.length;
        final avgBLevelSperms = results.fold<int>(0, (sum, r) => sum + r.numOfBLevelSperms) ~/ results.length;
        final avgCLevelSperms = results.fold<int>(0, (sum, r) => sum + r.numOfCLevelSperms) ~/ results.length;
        
        print('平均检测精子数: $avgDetectedSperms');
        print('平均A级精子数: $avgALevelSperms');
        print('平均B级精子数: $avgBLevelSperms');
        print('平均C级精子数: $avgCLevelSperms');
      }
    } else {
      print('没有找到视频文件');
    }
  }
  
  /// 示例：错误处理
  static Future<void> errorHandling() async {
    print('=== 错误处理示例 ===');
    
    final config = Configuration();
    final motility = Motility(config: config);
    
    // 测试不存在的文件
    final nonExistentPath = '/path/to/nonexistent/video.mp4';
    print('测试不存在的文件: $nonExistentPath');
    
    try {
      final result = await motility.analyze(nonExistentPath);
      if (result == null) {
        print('正确处理了不存在的文件');
      }
    } catch (e) {
      print('捕获到异常: $e');
    }
    
    // 测试空配置
    final motilityWithoutConfig = Motility(config: null);
    final videoPath = await _getSampleVideoPath();
    
    if (videoPath != null) {
      print('测试空配置...');
      try {
        final result = await motilityWithoutConfig.analyze(videoPath);
        print('空配置结果: $result');
      } catch (e) {
        print('空配置异常: $e');
      }
    }
  }
  
  /// 获取示例视频路径
  static Future<String?> _getSampleVideoPath() async {
    try {
      final tempDir = await getTemporaryDirectory();
      final samplePath = '${tempDir.path}/sample_video.mp4';
      
      // 检查是否存在示例视频
      final file = File(samplePath);
      if (await file.exists()) {
        return samplePath;
      }
      
      // 如果没有示例视频，返回null
      print('示例视频不存在: $samplePath');
      return null;
    } catch (e) {
      print('获取示例视频路径失败: $e');
      return null;
    }
  }
  
  /// 获取多个视频路径
  static Future<List<String>> _getMultipleVideoPaths() async {
    try {
      final tempDir = await getTemporaryDirectory();
      final videoDir = Directory('${tempDir.path}/videos');
      
      if (await videoDir.exists()) {
        final files = videoDir.listSync();
        return files
            .where((file) => file is File && file.path.endsWith('.mp4'))
            .map((file) => file.path)
            .toList();
      }
      
      return [];
    } catch (e) {
      print('获取视频文件列表失败: $e');
      return [];
    }
  }
  
  /// 运行所有示例
  static Future<void> runAllExamples() async {
    print('开始运行Motility Flutter版本示例...\n');
    
    await basicUsage();
    print('\n' + '='*50 + '\n');
    
    await customConfiguration();
    print('\n' + '='*50 + '\n');
    
    await batchProcessing();
    print('\n' + '='*50 + '\n');
    
    await errorHandling();
    print('\n' + '='*50 + '\n');
    
    print('所有示例运行完成！');
  }
}
